<?php

/**
 * @author  PVer
 * @date    2018-5-7 11:14:17
 * @version V1.0
 * @desc    
 */

namespace app\dkgzh\controller;

use cmf\controller\HomeBaseController;
use FontLib\Table\Type\name;
use think\Validate;
use app\user\model\UserModel;
use app\daikuan\model\LogisticsModel;
use app\daikuan\model\AuthrecordModel;
use app\daikuan\model\DriverrecordModel;
use app\daikuan\model\CodesModel;
use app\daikuan\model\RoleUserModel;
use app\daikuan\model\AboutModel;
use think\Db;
class UserController extends HomeBaseController {

    public function index() {
        $id = cmf_get_current_user_id();
        $userModel = new UserModel();
        $info = $userModel->where("id=" . $id)->find();
        if ($info['user_category'] != 1) {
            session(null);
            $user = [];
            cmf_update_current_user($user);
        }

        $this->assign('info', $info);
        return $this->fetch(':wyjkydl');
    }

//我要借款
    public function wyjkydl() {

    	$id = cmf_get_current_user_id();
    	  $userModel = new UserModel();
    	$info = $userModel->where("id=" . $id)->find();
    	$this->assign('info', $info);
        return $this->fetch();
    }

//我要还款
    public function index2ydl() {
    	$id = cmf_get_current_user_id();
    	$userModel = new UserModel();
    	$info = $userModel->where("id=" . $id)->find();
    	$this->assign('info', $info);
        return $this->fetch();
    }

//忘记密码
    public function wjmm() {
        return $this->fetch();
    }

//我的
    public function index3ydl() {
        $userModel = new UserModel();
        $loglist = $userModel->where("user_category=2")->select();
        $this->assign('logistics', $loglist);
        $id = cmf_get_current_user_id();
        $userModel = new UserModel();
        $info = $userModel->where("id=" . $id)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

//注册页面
    public function zcym() {
        return $this->fetch();
    }

//登录页
    public function dly() {
        return $this->fetch();
    }

//微信登录
    public function wxdlgl() {
        return $this->fetch();
    }

//微信登录回调
    public function wxlogin() {
        // $data = $this->request->post();
        $data = $this->request->get();
        $code = $data['code'];
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx3e2d3774771eed1e"
                . "&secret=23448b23332aed87479be0c0c70597c9&code=" . $code . "&grant_type=authorization_code";
        $res = json_decode(http_request($url, null), true);
        $openid = $res['openid'];

        //获取用户基本信息
        $access_token = $res['access_token'];
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
        $wxuser = json_decode(http_request($url, null), true);
        //var_dump($wxuser);
        $userModel = new UserModel();
        $user['gzh_open_id'] = $openid;
        $log = $userModel->doLoginGZH($user);
        if ($log == 0) {
            //var_dump($log);
            cmf_user_action('login');
            $this->redirect('dkgzh/user/wyjkydl');
        } else {
            //var_dump($log);
            $this->assign("wxuser", $wxuser);
            return $this->fetch();
        }
    }

    public function loginWXPost() {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'openid' => 'require',
                    //'yzm' => 'require',
            ]);
            $validate->message([
                'openid.require' => '公众号个人信息获取错误',
                    //  'yzm.require' => '请输入验证码1',
            ]);
            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $userModel = new UserModel();
            $user['user_pass'] = $data['password'];
            $user['user_login'] = $data['username'];
            $user['gzh_open_id'] = $data['openid'];
            $log = $userModel->doGZH($user);
            $session_login_http_referer = session('login_http_referer');
            $redirect = empty($session_login_http_referer) ? $this->request->root() : $session_login_http_referer;
            switch ($log) {
                case 0:
                    cmf_user_action('login');
                    $this->redirect('dkgzh/user/wyjkydl');
//return $this->fetch(':index');
                    break;
                case 1:
                    $this->error(lang('PASSWORD_NOT_RIGHT'));
                    return $this->fetch(':dly');
                    break;
                case 2:
                    $this->error('账户不存在');
                    return $this->fetch(':dly');
                    break;
                case 3:
                    $this->error('账号被禁止访问系统');
                    return $this->fetch(':dly');
                    break;
                default :
                    $this->error('未受理的请求');
                    return $this->fetch(':dly');
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':dly');
        }
    }

    public function wxloginPost() {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'username' => 'require',
                'password' => 'require|min:6|max:32',
            ]);
            $validate->message([
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空',
            ]);
            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $userModel = new UserModel();
            $user['user_pass'] = $data['password'];
            $user['user_login'] = $data['username'];
            $log = $userModel->doSJ($user);
            $session_login_http_referer = session('login_http_referer');
            $redirect = empty($session_login_http_referer) ? $this->request->root() : $session_login_http_referer;
            switch ($log) {
                case 0:
                    cmf_user_action('login');
                    $this->redirect('dkgzh/user/wyjkydl');
//return $this->fetch(':index');
                    break;
                case 1:
                    $this->error(lang('PASSWORD_NOT_RIGHT'));
                    return $this->fetch(':dly');
                    break;
                case 2:
                    $this->error('账户不存在');
                    return $this->fetch(':dly');
                    break;
                case 3:
                    $this->error('账号被禁止访问系统');
                    return $this->fetch(':dly');
                    break;
                default :
                    $this->error('未受理的请求');
                    return $this->fetch(':dly');
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':dly');
        }
    }

    //获取验证码
    public function getYzm() {
        $data = $this->request->post();
        $phone = $data['phone'];
        $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
        $new_code = rand(0001, 9999);
        $codesModel = new CodesModel();
        $arr = array();
        $arr['code'] = $new_code;
        $arr['phone'] = $phone;
        $codesModel->save($arr);
        $smsConf = array(
            'key' => config('juhekey'), //您申请的APPKEY
            'mobile' => $phone, //接受短信的用户手机号码
            'tpl_id' => '91468', //您申请的短信模板ID，根据实际情况修改
            'tpl_value' => "#code#=$new_code" //您设置的模板变量，根据实际情况修改
        );

        $content = $this->juhecurl($sendUrl, $smsConf, 1); //请求发送短信

        if ($content) {
            $result = json_decode($content, true);
            $error_code = $result['error_code'];
            if ($error_code == 0) {
                //状态为0，说明短信发送成功
                echo "短信发送成功";
            } else {
                //状态非0，说明失败
                $msg = $result['reason'];
                echo "短信发送失败(" . $error_code . ")：" . $msg;
            }
        } else {
            //返回内容异常，以下可根据业务逻辑自行修改
            echo "请求发送短信失败";
        }
    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    function juhecurl($url, $params = false, $ispost = 0) {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }

//修改姓名
    public function xmxg() {
        $id = cmf_get_current_user_id();
        if(!$id){
            $this->error('请登录后操作','/dkgzh/user/dly');
            //$this->redirect('portal/index/index');
        }
        $userModel = new UserModel();
        $user = cmf_get_current_user();
        $this->assign('info', $user);
        return $this->fetch();
    }

//退出登录
    public function logout() {
        $user = [];
        cmf_update_current_user($user);
        return $this->fetch(':user/index3ydl');
    }

//更换绑定手机号
    public function ghsjh() {
        $id = cmf_get_current_user_id();
        if(!$id){
            $this->error('请登录后操作','/dkgzh/user/dly');
            //$this->redirect('portal/index/index');
        }
        $userModel = new UserModel();
        $user = cmf_get_current_user();
        $this->assign('info', $user);
        return $this->fetch();
    }

//更改生日
    public function ggsr() {
        $userModel = new UserModel();
        $user = cmf_get_current_user();
        $this->assign('info', $user);
        return $this->fetch();
    }

//新生日更改
    public function xsrgg() {
        $id = cmf_get_current_user_id();
        if(!$id){
            $this->error('请登录后操作','/dkgzh/user/dly');
            //$this->redirect('portal/index/index');
        }
        $userModel = new UserModel();
        $user = cmf_get_current_user();
        $this->assign('info', $user);
        return $this->fetch();
    }

//身份认证
    public function sfrz() {
        $logModel = new UserModel();
        $loglist = $logModel->where("user_category=2")->select();
        $this->assign('logistics', $loglist);
        $id = cmf_get_current_user_id();
        if(!$id){
            $this->error('请登录后操作','/dkgzh/user/dly');
            //$this->redirect('portal/index/index');
        }
        $map = array();
        $map['a.user_category'] = 1;
        $map['a.id'] = $id;
        $info = db('user a ')->join(array(array('dk_driverrecord b', 'a.id=b.UserId', 'LEFT')
                    , array('dk_user c', 'a.logistics=c.id', 'LEFT')
                    , array('dk_authrecord d', 'a.id=d.UserId', 'LEFT')
                    , array('dk_driverrecord e', 'a.id=e.UserId', 'LEFT')
                ))
                ->field(' a.user_nickname,a.avatar,a.birthday,a.create_time,a.id,a.logistics,a.mobile,a.number,a.dk_status,(select count(*) from dk_driver_loan where DriverId=a.id and Status in (3,4)) isDaikuan,a.user_level,a.can_loan,a.can_loan_amount,d.Img1,d.Img2,d.Img3,d.Img4,e.Img1 Img5,e.Img2 Img6,e.Img3 Img7,e.Img4 Img8,c.user_nickname LogisticsName')
                ->where($map)
                ->find();
        $this->assign('info', $info);
        $this->assign('logistics', $loglist);
        return $this->fetch();
    }

//住址修改
    public function ggzz() {
        $id = cmf_get_current_user_id();
        $id = cmf_get_current_user_id();
        if(!$id){
            $this->error('请登录后操作','/dkgzh/user/dly');
        }
        $userModel = new UserModel();
        $info = $userModel->where("id=" . $id)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

//更改物流公司
    public function ggwlgs() {
        $logModel = new UserModel();
        $loglist = $logModel->where("user_category=2")->select();
        $this->assign('logistics', $loglist);
        $id = cmf_get_current_user_id();
        if(!$id){
            $this->error('请登录后操作','/dkgzh/user/dly');
        }
        $userModel = new UserModel();
        $info = $userModel->where("id=" . $id)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

//更改驾驶证认证信息
    public function sfrzxg() {
        $id = cmf_get_current_user_id();
        if(!$id){
            $this->error('请登录后操作','/dkgzh/user/dly');
        }
        $userModel = new UserModel();
        $info = $userModel->where("id=" . $id)->find();
        $res1 = Db::name('authrecord')->where("UserId=$id")->find();
        $this->assign('auth', $res1);
        $this->assign('info', $info);
        return $this->fetch();
    }

//更改驾驶证认证信息
    public function jszrz() {
        $id = cmf_get_current_user_id();
        if(!$id){
            $this->error('请登录后操作','/dkgzh/user/dly');
        }
        $userModel = new UserModel();
        $info = $userModel->where("id=" . $id)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

//关于我们
    public function gywm3x() {
        $aboutModel = new AboutModel();
        $info = $aboutModel->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

//修改密码
    public function ggmm() {
        $userModel = new UserModel();
        $id = cmf_get_current_user_id();
        if(!$id){
            $this->error('请登录后操作','/dkgzh/user/dly');
        }
        $user = cmf_get_current_user();

        $this->assign('info', $user);
        return $this->fetch();
    }

    public function loginPost() {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'username' => 'require',
                'password' => 'require|min:6|max:32',
            ]);
            $validate->message([
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空',
            ]);
            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $userModel = new UserModel();
            $user['user_pass'] = $data['password'];
            $user['user_login'] = $data['username'];
            $log = $userModel->doSJ($user);
            $session_login_http_referer = session('login_http_referer');
            $redirect = empty($session_login_http_referer) ? $this->request->root() : $session_login_http_referer;
            switch ($log) {
                case 0:
                    cmf_user_action('login');
                    $this->redirect('dkgzh/user/wyjkydl');
//return $this->fetch(':index');
                    break;
                case 1:
                    $this->error(lang('PASSWORD_NOT_RIGHT'));
                    return $this->fetch(':dly');
                    break;
                case 2:
                    $this->error('账户不存在');
                    return $this->fetch(':dly');
                    break;
                case 3:
                    $this->error('账号被禁止访问系统');
                    return $this->fetch(':dly');
                    break;
                default :
                    $this->error('未受理的请求');
                    return $this->fetch(':dly');
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':dly');
        }
    }

//忘记密码修改密码
    public function postWJMM() {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'username' => 'require',
                'password' => 'require|min:6|max:32',
            ]);
            $validate->message([
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空',
            ]);

            $data = $this->request->post();
            if($data['password'] != $data['password_format']){
                $this->error("两次密码输入不一致");
            }
            $user= Db::name('user')->where('user_login',$data['username'])->find();
            if(!$user){
                $this->error("用户不存在");
            }
            $userModel = new UserModel();
            $map['user_pass'] = cmf_password($data['password']);
            $result = Db::name('user')->where('user_login',$data['username'])->update($map);
            if ($result !== false) {
                $this->success("操作成功", url("portal/index/index"));
            } else {
                $this->error("操作失败");
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':zcym');
        }
    }

    public function registerPost() {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'username' => 'require',
                'password' => 'require|min:6|max:32',
            ]);
            $validate->message([
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空',
            ]);
            $data = $this->request->post();
            $code = $data['yzm'];
            $phone = $data['username'];
            // $sql = "select * from dk_codes where phone='$phone' order by createtime desc limit 1";
            $codeModel = new CodesModel();
           $p_code_table = $codeModel
                  ->where("phone=$phone")
                    ->order(["createtime" => "desc"])
                    ->find();
           $p_code = $p_code_table["code"];
            if ($p_code != $code) {
               $this->error("验证码错误");
            }

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $userModel = new UserModel();
            $user = array();
            $user['user_pass'] = cmf_password($data['password']);
            $user['user_login'] = $data['username'];
            $user['mobile'] = $data['username'];
            $user['user_nickname'] = $data['username'];
            $user['user_category'] = 1;
            $user['user_type'] = 4;
            $user['last_login_ip'] = get_client_ip(0, true);
            $user['create_time'] = time();
            $user['last_login_time'] = time();
            $user['user_status'] = 2;
            $isHave = $userModel->checkDriverCode($user);
            if ($isHave == 1) {
                $this->error("用户名已存在");
                exit();
            }
            if ($isHave == 2) {
                $this->error("手机号已经存在");
                exit();
            }
            $result_1 = $userModel->save($user);
            if ($result_1 > 0) {
                $roleUser = new RoleUserModel();
                $role = array();
                $role['role_id'] = 4;
                $role['user_id'] = $userModel->id;
                $roleUser->save($role);
                $data = $userModel->where('id', $userModel->id)->find();
                cmf_update_current_user($data);
                $token = cmf_generate_user_token($userModel->id, 'web');
                if (!empty($token)) {
                    session('token', $token);
                }
                $this->redirect('portal/index/index');
            } else {
                $this->error("请求错误");
                return $this->fetch(':zcym');
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':zcym');
        }
    }

//修改密码
    public function postModifyPass() {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'old' => 'require',
                'new' => 'require',
            ]);
            $validate->message([
                'old.require' => '请输入原密码',
                'new.require' => '新密码不能为空',
            ]);
            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            $oldModel = new UserModel();
            $old = $data["old"];
            $oldUser = $oldModel->where("id=" . $data["id"])->find();
            if (cmf_compare_password($old, $oldUser["user_pass"])) {

                $userModel = new UserModel();
                $user = array();
                $user['user_pass'] = cmf_password($data['new']);
                $result = $userModel->save($user, 'id=' . $data['id']);
                if ($result !== false) {
                    $this->success("操作成功", url("index3ydl"));
                } else {
                    $this->error("操作失败");
                }
            } else {
                $this->error("密码错误");
                return $this->fetch();
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':zcym');
        }
    }

//修改用户名
    public function postModifyNickName() {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'newname' => 'require',
            ]);
            $validate->message([
                'newname.require' => '新的用户名不能为空',
            ]);
            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $userModel = new UserModel();
            $user = array();
            $user['user_nickname'] = $data['newname'];
            $result = $userModel->save($user, 'id=' . $data['id']);
            $map = array();
            $map["id"] = $data['id'];
            $map["user_category"] = 1;
            $newinfo = $userModel->where($map)->find();
            session('user', $newinfo->toArray());
            if ($result !== false) {
                $this->success("操作成功", url("index3ydl"));
            } else {
                $this->error("操作失败");
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':zcym');
        }
    }

//修改住址
    public function postModifyZZ() {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'address' => 'require',
            ]);
            $validate->message([
                'address.require' => '新的住址不能为空',
            ]);
            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $userModel = new UserModel();
            $user = array();
            $user['address'] = $data['address'];
            $result = $userModel->save($user, 'id=' . $data['id']);
            if ($result !== false) {
                $this->success("操作成功", url("index3ydl"));
            } else {
                $this->error("操作失败");
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':zcym');
        }
    }

    //修改物流公司
    public function postModifyWLGS() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $userModel = new UserModel();
            $user = array();
            $user['logistics'] = $data['newlogistics'];
            $result = $userModel->save($user, 'id=' . $data['id']);
            if ($result !== false) {
                $this->success("操作成功", url("index3ydl"));
            } else {
                $this->error("操作失败");
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':zcym');
        }
    }

//司机认证
    public function postDriverRZ() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $driverrecordModel = new DriverrecordModel();
            $arr = array();
            $arr['UserId'] = $data['id'];
            $arr['Img1'] = $data['imgid1'];
            $arr['Img2'] = $data['imgid2'];
            $arr['Img3'] = $data['imgid3'];
            $arr['Img4'] = $data['imgid4'];
            $res2 = $driverrecordModel->where('UserId=' . $data['id'])->select();
            if (count($res2) > 0) {
                $result_3 = $driverrecordModel->save($arr, 'UserId=' . $data['id']);
            } else {
                $result_3 = $driverrecordModel->save($arr);
            }
            if ($result !== false) {
                $this->success("操作成功", url("index3ydl"));
            } else {
                $this->error("操作失败");
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':zcym');
        }
    }

    //身份证+驾驶证认证
    public function postAllRZ() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(!$data['id']){
                $this->error('请登录后操作','/dkgzh/user/dly');
                //$this->redirect('portal/index/index');
            }
            //修改身份证
            $userModel = new UserModel();
            $user = array();
            $user['user_nickname'] = $data['user_nickname'];
            $user['number']         =  $data['number'];
            $user['logistics'] = $data['newlogistics'];
            $user['dk_status'] = 3;
            $result_1 = $userModel->save($user, 'id=' . $data['id']);
            //司机认证信息
            $authrecordModel = new AuthrecordModel();
            $arr = array();
            $arr['UserId'] = $data['id'];
            $arr['Img1'] = $data['imgid1'];
            $arr['Img2'] = $data['imgid2'];
            $arr['Img3'] = $data['imgid3'];
            $arr['Img4'] = $data['imgid4'];
            $res1 = $authrecordModel->where('UserId=' . $data['id'])->select();
            if (count($res1) > 0) {
                $result_2 = $authrecordModel->save($arr, 'UserId=' . $data['id']);
            } else {
                $result_2 = $authrecordModel->save($arr);
            }

            //驾驶证认证
            $driverrecordModel = new DriverrecordModel();
            $arr1 = array();
            $arr1['UserId'] = $data['id'];
            $arr1['Img1'] = $data['imgid5'];
            $arr1['Img2'] = $data['imgid6'];
            $arr1['Img3'] = $data['imgid7'];
            $arr1['Img4'] = $data['imgid8'];
            $res2 = $driverrecordModel->where('UserId=' . $data['id'])->select();
            if (count($res2) > 0) {
                $result_3 = $driverrecordModel->save($arr1, 'UserId=' . $data['id']);
            } else {
                $result_3 = $driverrecordModel->save($arr1);
            }

            if ($result_1 !== false && $result_2 !== false && $result_3 !== false) {
                $this->success("操作成功", url("index3ydl"));
            } else {
                $this->error("操作失败");
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':zcym');
        }
    }

//身份证认证
    public function postShenfenRZ() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $authrecordModel = new AuthrecordModel();
            $id = $data["id"];
            $arr = array();
            $arr['UserId'] = $data['id'];
            $arr['Img1'] = $data['imgid1'];
            $arr['Img2'] = $data['imgid2'];
            $arr['Img3'] = $data['imgid3'];
            $arr['Img4'] = $data['imgid4'];
            $arr2 = array();
            $arr2['user_nickname'] = $data['user_nickname'];
            $arr2['birthday'] = $data['birthday'];
            $arr2['number'] = $data['number'];
            $arr2['address'] = $data['address'];
            $arr2['dk_status']=3;
            $res1 = $authrecordModel->where("UserId=$id")->select();
            Db::name('user')->where('id',$id)->update($arr2);
            if (count($res1) > 0) {
                $result = $authrecordModel->save($arr, "UserId=$id");
            } else {
                $result = $authrecordModel->save($arr);
            }
            if ($result !== false) {
                $this->success("操作成功", url("index3ydl"));
            } else {
                $this->error("操作失败");
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':zcym');
        }
    }

//更改生日
    public function postModifyBirthday() {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'birthday' => 'require',
            ]);
            $validate->message([
                'birthday.require' => '新的生日不能为空',
            ]);
            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $userModel = new UserModel();
            $user = array();
            $user['birthday'] = strtotime($data['birthday']);
            $result = $userModel->save($user, 'id=' . $data['id']);
            if ($result !== false) {
                $this->success("操作成功", url("index3ydl"));
            } else {
                $this->error("操作失败");
            }
        } else {
            $this->error("请求错误");
            return $this->fetch(':zcym');
        }
    }

//上传图片
    public function upload() {
        $files = array();
        $success = 0;    //用户统计有多少张图片上传成功了

        foreach ($_FILES as $item) {
            $index = count($files);
            $files[$index]['srcName'] = $item['name'];    //上传图片的原名字
            $files[$index]['error'] = $item['error'];    //和该文件上传相关的错误代码
            $files[$index]['size'] = $item['size'];        //已上传文件的大小，单位为字节
            $files[$index]['type'] = $item['type'];        //文件的 MIME 类型，需要浏览器提供该信息的支持，例如"image/gif"
            $files[$index]['success'] = false;            //这个用于标志该图片是否上传成功
            $files[$index]['path'] = '';                //存图片路径
            // 接收过程有没有错误
            if ($item['error'] != 0)
                continue;
            //判断图片能不能上传
            if (!is_uploaded_file($item['tmp_name'])) {
                $files[$index]['error'] = 8000;
                continue;
            }
            //扩展名
            $extension = '';
            if (strcmp($item['type'], 'image/jpeg') == 0) {
                $extension = '.jpg';
            } else if (strcmp($item['type'], 'image/png') == 0) {
                $extension = '.png';
            } else if (strcmp($item['type'], 'image/gif') == 0) {
                $extension = '.gif';
            } else {
                //如果type不是以上三者，我们就从图片原名称里面去截取判断去取得(处于严谨性)    
                $substr = strrchr($item['name'], '.');
                if (FALSE == $substr) {
                    $files[$index]['error'] = 8002;
                    continue;
                }

                //取得元名字的扩展名后，再通过扩展名去给type赋上对应的值
                if (strcasecmp($substr, '.jpg') == 0 || strcasecmp($substr, '.jpeg') == 0 || strcasecmp($substr, '.jfif') == 0 || strcasecmp($substr, '.jpe') == 0) {
                    $files[$index]['type'] = 'image/jpeg';
                } else if (strcasecmp($substr, '.png') == 0) {
                    $files[$index]['type'] = 'image/png';
                } else if (strcasecmp($substr, '.gif') == 0) {
                    $files[$index]['type'] = 'image/gif';
                } else {
                    $files[$index]['error'] = 8003;
                    continue;
                }
                $extension = $substr;
            }

            //对临时文件名加密，用于后面生成复杂的新文件名
            $md5 = md5_file($item['tmp_name']);
//        //取得图片的大小
            $imageInfo = getimagesize($item['tmp_name']);
            $rawImageWidth = $imageInfo[0];
            $rawImageHeight = $imageInfo[1];
            $path = UPLOAD_ROOT . '/upload/' . date('Ymd') . '/';
            $url = '/upload/' . date('Ymd') . '/';

            if (!file_exists($path)) {
                mkdir($path, 0766, true);
                chmod($path, 0766);
                chmod($path, 0777);
            } else if (!is_writable($path)) {
                chmod($path, 0766);
                chmod($path, 0777);
                if (!is_writable($dir)) {
                    throw new FileSystemException("目录 $dir 不可写");
                }
            }
            $name = "$md5.0x{$rawImageWidth}x{$rawImageHeight}{$extension}";
            $ret = file_exists($path . $name) ? true : move_uploaded_file($item['tmp_name'], $path . $name);
            if ($ret === false) {
                $files[$index]['error'] = 8004;
                continue;
            } else {
                $files[$index]['path'] = $url . $name;     //存图片路径
                $files[$index]['success'] = true;            //图片上传成功标志
                $files[$index]['width'] = $rawImageWidth;    //图片宽度
                $files[$index]['height'] = $rawImageHeight;    //图片高度
                $success ++;    //成功+1
            }
        }
//将图片已json形式返回给js处理页面  ，这里大家可以改成自己的json返回处理代码
        echo json_encode(array(
            'total' => count($files),
            'success' => $success,
            'files' => $files,
        ));
    }

//这里我附上ensure_writable_dir()函数的代码
    /**
     * 确保文件夹存在并可写
     *
     * @param string $dir
     */
    function ensure_writable_dir($dir) {

        if (!file_exists($dir)) {
            mkdir($dir, 0766, true);
            chmod($dir, 0766);
            chmod($dir, 0777);
        } else if (!is_writable($dir)) {
            chmod($dir, 0766);
            chmod($dir, 0777);
            if (!is_writable($dir)) {
                throw new FileSystemException("目录 $dir 不可写");
            }
        }
    }

}
